package com.example.busshop.entity;

import com.example.busshop.common.entity.LogicEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
@Entity
@Setter
@Getter
@Table(name = "orders")
@Where(clause = "is_deleted=0")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"},ignoreUnknown = true)
public class Order extends LogicEntity {
    /**
     * 0 未支付 1 已支付 2 已确认 3
     * @return
     */
    @Column
    private Integer status;
    @ManyToOne(fetch = FetchType.LAZY)
    private Shop shop;
    @ManyToOne(fetch = FetchType.LAZY)
    private Customer customer;
    @OneToMany(mappedBy = "order",
    fetch = FetchType.LAZY,
    orphanRemoval = true,
    cascade = CascadeType.ALL)
    @JsonIgnore
    private Set<LineItem> lineItems;
    public Set<LineItem> addItem(Item item,Double quantity){
        LineItem lineItem=findLineItem(item);
        if(lineItem==null){
            lineItem=new LineItem();
            lineItem.setItem(item);
            lineItem.setQuantity(quantity);
            lineItems.add(lineItem);
        }
        else{
            lineItem.setQuantity(lineItem.getQuantity()+quantity);
        }
        return lineItems;
    }
    private LineItem findLineItem(Item item){
        AtomicReference<LineItem> result=new AtomicReference<>(null);
        lineItems.forEach(lineItem -> {
            if(lineItem.getItem().equals(item))
                result.set(lineItem);
        });
        return result.get();
    }

}
